<template>
  <!-- 专利趋势分析(新设计包含总量，实用新型，发明专利) -->
  <div>
    <div :id="chartId" class="chart"></div>
  </div>
</template>

<script>
import { mapState } from "vuex";
import Ecolors from "@/utils/chartColors";
import { resize, spaceTxt, thousands } from "@/utils/utils";
import * as echarts from "echarts";

export default {
  mixins: [resize],
  props: {
    chartId: {
      type: String
    },
    chartData: {
      type: Object
    }
  },
  data() {
    return {
      chart: null,
      graphType: "bar",
      colors: [],
      xData: [],
      yData: [],
      legendData: []
    };
  },
  computed: {
    ...mapState(["curChartConfig"])
  },
  watch: {
    curChartConfig: {
      deep: true,
      handler: function() {
        this.getCurChartConfig();
      }
    },
    chartData: {
      deep: true,
      handler: function() {
        if (Object.keys(this.chartData).length <= 0) {
          if (this.chart) this.chart.clear();
        } else {
          // console.log(222);
          // console.log(222,this.chartData);
          this.getCurChartConfig();
        }
      }
    }
  },
  mounted() {
    this.chart = this.$echarts.init(document.getElementById(this.chartId));
    this.$emit("domRef", document.getElementById(this.chartId))
    this.getCurChartConfig();
  },
  methods: {
    getCurChartConfig() {
      if (Object.keys(this.curChartConfig).length > 0) {
        let colors = [];
        this.curChartConfig.colors.forEach(v => {
          colors.push(v.color);
        });
        this.colors = [...colors, ...Ecolors.color];
        let graphType = this.curChartConfig.graphType;
        if (this.curChartConfig.graphType === "bar") {
          graphType = "bar";
        } else if (this.curChartConfig.graphType === "bar1") {
          graphType = "bar";
        } else if (this.curChartConfig.graphType === "bar2") {
          graphType = "bar";
        } else if (this.curChartConfig.graphType === "line") {
          graphType = "line";
        }
        this.graphType = graphType;
      }
      if (Object.keys(this.chartData).length > 0) {
        this.initbar();
      }
    },
    getSeriesData() {
      let seriesData = {
        all: [],
        shouquan: [],
        notshouquan: [],
        shouquanlv: [],
        xarr: []
      };
      let newChartData = JSON.parse(JSON.stringify(this.chartData));
      let xarr = [];
      newChartData.apd.map(item => {
        xarr.push(item.key_as_string);
      });
      xarr = Array.from(new Set(xarr));
      xarr = xarr.sort((a, b) => {
        var dateA = new Date(a);
        var dateB = new Date(b);
        return dateA - dateB;
      });
      let all = [];
      let shouquan = [];
      let notshouquan = [];
      let shouquanlv = [];
      xarr.map(item => {
        let i = newChartData.apd.findIndex(it => {
          return item == it.key_as_string;
        });
        i > -1 ? all.push(newChartData.apd[i].doc_count || 0) : all.push(0);
        i > -1
          ? shouquan.push(newChartData.apd[i].leg_det[0]?.doc_count || 0)
          : shouquan.push(0);
        i > -1
          ? notshouquan.push(newChartData.apd[i].leg_det[1]?.doc_count || 0)
          : notshouquan.push(0);
        i > -1
          ? shouquanlv.push(newChartData.apd[i].leg_det[2]?.doc_count || 0)
          : shouquanlv.push(0);
      });

      seriesData = {
        all: all,
        shouquan: shouquan,
        notshouquan: notshouquan,
        shouquanlv: shouquanlv,
        xarr: xarr
      };
      // console.log("seriesData", seriesData);
      return seriesData;
    },
    initbar() {
      let seriesData = this.getSeriesData();
      // x轴分隔线
      let xSplitLine = {
        show: this.curChartConfig["xGridLine"].checked,
        lineStyle: {
          color: this.curChartConfig["xGridLine"].color || "#f0f1f3",
          type: this.curChartConfig["xGridLine"].type
        }
      };
      // y轴分隔线
      let ySplitLine = {
        show:
          this.curChartConfig["yGridLine"] &&
          this.curChartConfig["yGridLine"].checked,
        lineStyle: {
          color:
            (this.curChartConfig["yGridLine"] &&
              this.curChartConfig["yGridLine"].color) ||
            "#f0f1f3",
          type: this.curChartConfig["yGridLine"].type
        }
      };
      let color = [
        "#0092f6",
        "#00d4c7",
        "#aecb56",
        "#FF515A",
        "#8B5CFF",
        "#00CA69"
      ];
      // 背景色
      let backgroundColor = this.curChartConfig["showBgColor"].checked
        ? this.curChartConfig["showBgColor"].color
        : "#fff";
      let option = {
        color: color,
        title: {
          text: ""
        },
        tooltip: {
          trigger: "axis",
          axisPointer: {
            // type: "shadow",
          },
          formatter: params => {
            var res = "";
            for (var i = 0; i < params.length; i++) {
              if (params[i].seriesName != "总计") {
                // 这行代码就是判断语句 具体情况 具体分析  自己打印params 来实现自己的判断
                let str_span1 = `<span >${params[i].data}%</span>`
                let str_span2 = `<span >${params[i].data}</span>`
                res += `<div style="background:none">
                  ${params[i].seriesName}：
                  ${params[i].seriesName == "授权率" ? str_span1 : str_span2 }  
                </div>`;
              }
            }
            return res; //最后返回的数据得一个字符串 并且支持html css 显示我用的都是行内式样式 拼接成一个字符串 给最后显示 数遍悬浮的样式也是在这里设置 你的字符串是什么样式  渲染出来就是什么样的
          }
        },
        legend: {
          show: this.curChartConfig["showLegend"],
          x: "center",
          y: "0",
          icon: "stack",
          itemWidth: 10,
          itemHeight: 10,
          textStyle: {
            color: "#1bb4f6"
          },
          data: ["授权", "非授权", "授权率"]
        },
        // 背景色
        backgroundColor: backgroundColor,
        toolbox: {
          feature: {
            // saveAsImage: {}
          }
        },
        xAxis: [
          {
            type: "category",
            boundaryGap: true,
            splitLine: xSplitLine,
            data: seriesData.xarr
          }
        ],
        yAxis: [
          {
            type: "value",
            name: '授权/非授权',
            scale: true,
            splitLine: ySplitLine,
            minInterval: 1
          },
          // {
          //   type: "value",
          //   show: false,
          //   interval: 1,
          //   axisLabel: {
          //     show: true,
          //     interval: "auto",
          //     formatter: "{value} %"
          //   }
          // },
          {
            type: 'value',
            name: '授权率',
            position: 'right',
            splitLine: ySplitLine,
            min: 0,
            max: 100,
            // alignTicks: true,
            // axisLine: {
            //   show: true,
            //   lineStyle: {
            //     // color: colors[0]
            //   }
            // },
            axisLabel: {
              formatter: '{value}%'
            }
          },
        ],
        smooth: false,
        series: []
      };
      let series = []
      if (this.graphType === "line") {
        series = [
          {
            name: "授权",
            type: this.graphType,
            symbol: "circle",
            symbolSize: 8,
            label: {
              normal: {
                show: this.curChartConfig["showLabel"] || false,
                position: "top",
                color: "#6b6c7e",
                fontSize: this.curChartConfig["fontSize"] || 12,
              }
            },
            itemStyle: {
              normal: {
                color: "#0092f6",
                lineStyle: {
                  color: "#0092f6",
                  width: 1
                },
                areaStyle: {
                  //color: '#94C9EC'
                  color: new echarts.graphic.LinearGradient(0, 1, 0, 0, [
                    {
                      offset: 0,
                      color: "rgba(255,255,255,0.1)"
                    },
                    {
                      offset: 1,
                      color: "rgba(0,213,245,1)"
                    }
                  ])
                }
              }
            },
            data: seriesData.shouquan
          },
          {
            name: "非授权",
            type: this.graphType,
            symbol: "circle",
            symbolSize: 8,
            label: {
              normal: {
                show: this.curChartConfig["showLabel"] || false,
                position: "top",
                color: "#6b6c7e",
                fontSize: this.curChartConfig["fontSize"] || 12,
              }
            },
            itemStyle: {
              normal: {
                color: "#00d4c7",
                lineStyle: {
                  color: "#00d4c7",
                  width: 1
                },
                areaStyle: {
                  //color: '#94C9EC'
                  color: new echarts.graphic.LinearGradient(0, 1, 0, 0, [
                    {
                      offset: 0,
                      color: "rgba(255,255,255,0.1)"
                    },
                    {
                      offset: 1,
                      color: "rgba(0,212,199,1)"
                    }
                  ])
                }
              }
            },
            data: seriesData.notshouquan
          },
          {
            name: "授权率",
            type: "line",
            symbol: "circle",
            symbolSize: 8,
            smooth: false,
            yAxisIndex: 1,
            label: {
              normal: {
                show: this.curChartConfig["showLabel"] || false,
                position: "top",
                color: "#6b6c7e",
                fontSize: this.curChartConfig["fontSize"] || 12,
              }
            },
            itemStyle: {
              normal: {
                // color: "#0eddfd",
                color: "#EC7125",
                label: {
                  show: false,
                  position: "top",
                  formatter: "{c}%",
                  borderWidth: 10,
                  // color: "#0eddfd",
                  color: "#EC7125",
                  padding: 4
                },
                labelLine: {
                  show: false
                }
              }
            },
            data: seriesData.shouquanlv
          },
          // {
          //   name: "总计",
          //   type: "bar",
          //   stack: "sum",
          //   label: {
          //     normal: {
          //       show: false,
          //       position: "top",
          //       formatter: function(p) {
          //         let num =
          //           (seriesData.notshouquan[p.dataIndex]
          //             ? seriesData.notshouquan[p.dataIndex]
          //             : 0) +
          //           (seriesData.shouquan[p.dataIndex]
          //             ? seriesData.shouquan[p.dataIndex]
          //             : 0);
          //         return "总 " + thousands(num);
          //       },
          //       textStyle: { color: "rgba(0,212,199,1)" }
          //     }
          //   },
          //   emphasis: {
          //     focus: "series"
          //   },
          //   data: seriesData.all.map(it => (it = 0))
          // }
        ]
      } else if (this.graphType === "bar") {
        series = [
          {
            name: "授权",
            stack: "sum",
            type: this.graphType,
            barMaxWidth: 35,
            barMinWidth: 8,
            itemStyle: {
              normal: {
                label: {
                  show: this.curChartConfig["showLabel"] || false,
                  textStyle: {
                    color: "#fff"
                  },
                  position: "inside",
                  fontSize: this.curChartConfig["fontSize"] || 12,
                  formatter: function(p) {
                    return p.value > 0 ? thousands(p.value || 0) : "";
                  }
                }
              }
            },

            data: seriesData.shouquan
          },
          {
            name: "非授权",
            type: this.graphType,
            stack: "sum",
            barMaxWidth: 35,
            barMinWidth: 8,
            itemStyle: {
              normal: {
                label: {
                  show: this.curChartConfig["showLabel"] || false,
                  fontSize: this.curChartConfig["fontSize"] || 12,
                  textStyle: {
                    color: "#fff"
                  },
                  position: "inside",
                  formatter: function(p) {
                    return p.value > 0 ? thousands(p.value || 0) : "";
                  }
                }
              }
            },
            data: seriesData.notshouquan
          },
          {
            name: "授权率",
            type: "line",
            // stack: "sum",
            symbol: "circle",
            symbolSize: 8,
            smooth: false,
            yAxisIndex: 1,
            itemStyle: {
              normal: {
                // color: "#0eddfd",
                color: "#EC7125",
                label: {
                  show: this.curChartConfig["showLabel"] || false,
                  fontSize: this.curChartConfig["fontSize"] || 12,
                  position: "top",
                  formatter: "{c}%",
                  borderWidth: 10,
                  // color: "#0eddfd",
                  color: "#EC7125",
                  padding: 4
                },
                labelLine: {
                  show: false
                }
              }
            },
            data: seriesData.shouquanlv
          },
          {
            name: "总计",
            type: "bar",
            stack: "sum",
            label: {
              normal: {
                show: false,
                position: "top",
                formatter: function(p) {
                  let num =
                    (seriesData.notshouquan[p.dataIndex]
                      ? seriesData.notshouquan[p.dataIndex]
                      : 0) +
                    (seriesData.shouquan[p.dataIndex]
                      ? seriesData.shouquan[p.dataIndex]
                      : 0);
                  return "总 " + thousands(num);
                },
                textStyle: { color: "rgba(0,212,199,1)" }
              }
            },
            emphasis: {
              focus: "series"
            },
            data: seriesData.all.map(it => (it = 0))
          }
        ]
      }
      option.series = series

      if (this.graphType !== "pie") {
        option.tooltip.trigger = "axis";
      } else {
        let formatter = params => {
          let str = `${params.marker}${params.data.name}：${params.data.value}`;
          return str;
        };
        option.grid = {
          top: "20px",
          right: "20px",
          left: "20px",
          bottom: "20px",
          containLabel: true
        };
        option.tooltip.trigger = "item";
        option.tooltip.formatter = formatter;
        option.xAxis.show = false;
        option.yAxis.show = false;
      }
      this.chart.clear();
      this.chart.setOption(option);
      this.$emit("chartDom", this.chart);

      // 点击进行对比分析
      // this.chart.off("click");
      // this.chart.on("click", params => {
      //   let dataIndex = params.dataIndex;
      //   let op = this.chart.getOption();
      //   op.series[0].data.forEach((v, i) => {
      //     if (i == dataIndex) {
      //       if (v.custom_selected === true) {
      //         v.itemStyle.color = v.custom_color;
      //       } else {
      //         v.itemStyle.color = "red";
      //       }
      //       v.custom_selected = !v.custom_selected;
      //     }
      //   });
      //   this.getContrastiveData(op);
      //   this.chart.setOption(op);
      // });

      // 后台报告下载
      this.chart.on("finished", () => {
        let tempId = this.$route.query.tempId;
        if (tempId) {
          this.getEchartImg(this.chart.getDataURL());
        }
      });
    },

    getEchartImg(base) {
      let dom = document.getElementById("echartImgFinished");
      if (dom) {
        document.getElementById("app").removeChild(dom);
      }
      window.echartImg = base;
      let _echartImg = document.createElement("div");
      _echartImg.setAttribute("id", "echartImgFinished");
      document.getElementById("app").appendChild(_echartImg);
    },
    // 保存对比分析数据
    getContrastiveData(option) {
      let arr = [];
      option.series[0].data.forEach((v, i) => {
        if (v.custom_selected === true) {
          arr.push(v);
        }
      });
      this.$emit("contrastiveData", arr);
    }
  },

  destroyed() {
    this.chart.dispose();
    this.chart = null;
  }
};
</script>

<style lang="scss" scoped>
// .chart {
//   background-color: #fff;
// }
</style>
